package org.jvm.rtda.heap.symref;

import org.jvm.rtda.heap.*;
import org.jvm.rtda.heap.classmember.Method;
import org.jvm.rtda.thread.Thread;

/**
 * 接口方法引用
 *
 * @author 王思翔
 * @date 2023/2/4
 */
public class InterfaceMethodRef extends MemberRef {

    private Method method;


    public InterfaceMethodRef(ConstantPool cp, String className, String name, String descriptor) {
        super(cp, className, name, descriptor);
    }

    /**
     * 解析方法引用
     *
     * @return
     */
    public Method resolveMethodRef(Thread thread) {
        //检查类是否是接口，接口方法引用的引用类必须是接口
        Klass thatClass = this.resolvedClass(thread);
        if (!thatClass.isInterface()) {
            throw new RuntimeException("class is not interface");
        }
        //查找类
        Method method = MethodUtil.lookupMethodInInterfaces(new Klass[]{thatClass}, this.name, this.descriptor);
        if (method == null) {
            throw new RuntimeException("method no found");
        }
        //检查权限
        if (!method.isAccessibleTo(this.cp.getKlass())) {
            throw new RuntimeException("method can not accessible");
        }
        this.method = method;
        return method;
    }
}
